{% extends 'base_pages/base.html' %}

{% block title %}
{{_("Background Tasks")}}
{% endblock %}

{% block header %}
<h1>{{_("Background Tasks")}}</h1>
{% endblock %}

{% block content %}
<body>
    <!-- < 根据 baseapp.py 中的 routes 模板变量创建一系列超链接 -->

    <table id="taskTable">
        <thead>
            <tr>
                <th>{{_("Task ID")}}</th>
                <th>{{_("Task Name")}}</th>
                <th>{{_("Started At")}}</th>
                <th>{{_("Finished At")}}</th>
                <th>{{_("Status")}}</th>
                <th>{{_("Actions")}}</th>
            </tr>
        </thead>
        <tbody>
            <!-- Task rows will be dynamically inserted here -->
        </tbody>
    </table>

    {% include 'components/task_logs.html' %}

    <script>
        // <!-- let currentTaskId = null; -->
        //let logInterval = null;

        // Function to fetch and display all tasks
        function fetchTasks() {
            apiFetch('background_tasks/tasks')
                .then(response => response.json())
                .then(data => {
                    const taskTableBody = document.querySelector("#taskTable tbody");
                    taskTableBody.innerHTML = ""; // Clear existing rows
                    data.forEach(task => {
                        const row = document.createElement("tr");
                        row.innerHTML = `
                            <td>${task.task_id}</td>
                            <td>${task.display_name}</td>
                            <td>${formatTimestamp(task.started_at)}</td>
                            <td>${formatTimestamp(task.finished_at)}</td>
                            <td>${task.status}</td>
                            <td>
                                <button onclick="openTaskLogModal('${task.task_id}')">View Log</button>
                            </td>
                        `;
                        taskTableBody.appendChild(row);
                    });
                })
                .catch(error => { console.error('Error fetching tasks:', error); console.log(error) });
        }

        // Call fetchTasks when the page loads
        window.onload = fetchTasks;
    </script>
</body>
{% endblock %}